#include "MultipluginsTest.h"
#include <qcoreapplication.h>
#include <qdir.h>
#include <qpluginloader.h>


#include "CPlugExtendDlg.h"

#define PLUG_PATH QCoreApplication::applicationDirPath()+"/plugins"

#pragma execution_character_set("utf-8")
MultipluginsTest::MultipluginsTest(QWidget *parent)
    : QMainWindow(parent), m_help_menu{}, m_about_plug{}, m_plug_filenames{}
{
    ui.setupUi(this);
    OnInitDialog();
}

MultipluginsTest::~MultipluginsTest()
{}

void MultipluginsTest::OnInitDialog()
{
    CreateMenus();
    CreateActions();
    LoadPlugins();
}

void MultipluginsTest::OnAboutPlugIn()
{
    CPlugExtendDlg _dlg(PLUG_PATH, m_plug_filenames, this);
    _dlg.exec();
}

void MultipluginsTest::CreateMenus()
{
    if (nullptr == m_help_menu)
        m_help_menu = this->menuBar()->addMenu(tr("&Help"));
    Q_ASSERT(m_help_menu);
}

void MultipluginsTest::CreateActions()
{
    if (nullptr == m_about_plug)
        m_about_plug = new QAction(tr("About &Plug"), this);
    Q_ASSERT(m_about_plug);
    connect(m_about_plug,&QAction::triggered,this,&MultipluginsTest::OnAboutPlugIn);
    if (m_help_menu)
        m_help_menu->addAction(m_about_plug);
}

void MultipluginsTest::LoadPlugins()
{
    QDir _plug_dir(PLUG_PATH);
    const auto entrylst = _plug_dir.entryList(QDir::Files);
    for (const auto& i : entrylst)
    {
        QPluginLoader _loader(_plug_dir.absoluteFilePath(i));
        auto _plugin = _loader.instance();
        if (_plugin)
            m_plug_filenames += i;
    }
}
